<!DOCTYPE html>
<html lang="en">
<head>
    #include("../include/header.html")
    <style type="text/css">
        .ztree li span.button.add {
            margin-left: 2px;
            margin-right: -1px;
            background-position: -144px 0;
            vertical-align: top;
            *vertical-align: middle
        }
    </style>

    <!-- [1] 需要引入 font-awesome.css 和 awesome.css，并且不要引入 zTreeStyle.css -->
    <link rel="stylesheet" href="http://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="http://cdn.staticfile.org/zTree.v3/3.5.28/css/awesomeStyle/awesome.min.css">
    <style media="screen">
        .node_name {
            font-size: 14px;
            margin-left: 2px;
        }

        .ztree li a {
            margin-bottom: 3px;
        }

        .ztree, .ztree * {
            background: white;
        }

        .ztree, .ztree li a,
        .ztree li span.button::before,
        .ztree li span.button.ico_open::before,
        .ztree li span.button.ico_close::before,
        .ztree li span.button.ico_docu::before,
        span.tmpzTreeMove_arrow::before {
            color: #444;
        }

        .ztree li a.curSelectedNode {
            background-color: white;
            color: darkred;
        }
    </style>
</head>
<body>

<div class="container">
    #include("../include/menu.html")

    <div class="row">
        <div class="col-md-3">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h4 class="panel-title">
                        <a data-toggle="collapse" data-parent="#accordion" href="#interfaceList">
                            接口列表
                        </a>
                    </h4>
                </div>
                <div id="interfaceList" class="panel-collapse collapse in">
                    <div class="panel-body">
                        <ul id="treeDemo" class="ztree" style="height: 300px;overflow: auto;"></ul>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-9" id="right-view">
            <div class="row">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">
                            <a data-toggle="collapse" data-parent="#accordion" href="#interfaceRequest">
                                请求信息
                            </a>
                            <button onclick="addRowByTableId('interfaceRequestTable')" type="button"
                                    class="btn btn-primary btn-xs">
                                <i class="fa fa-plus" aria-hidden="true"></i>
                                新增
                            </button>

                            <button onclick="saveRowsByTableId('interfaceRequestTable');" type="button"
                                    class="btn btn-primary btn-xs">
                                <i class="fa fa-floppy-o" aria-hidden="true"></i>
                                保存
                            </button>
                        </h4>
                    </div>
                    <div id="interfaceRequest" class="panel-collapse collapse in">
                        <div class="panel-body">
                            <table id="interfaceRequestTable">
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h4 class="panel-title">
                            <a data-toggle="collapse" data-parent="#accordion" href="#interfaceResponse">
                                响应信息
                            </a>
                            <button onclick="addRowByTableId('interfaceResponseTable')" type="button"
                                    class="btn btn-primary btn-xs">
                                <i class="fa fa-plus" aria-hidden="true"></i>
                                新增
                            </button>

                            <button onclick="saveRowsByTableId('interfaceResponseTable');" type="button"
                                    class="btn btn-primary btn-xs">
                                <i class="fa fa-floppy-o" aria-hidden="true"></i>
                                保存
                            </button>

                            <button onclick="importFromJson('interfaceResponseTable')" type="button"
                                    class="btn btn-primary btn-xs pull-right">
                                <i class="fa fa-plus" aria-hidden="true"></i>
                                JSON导入
                            </button>
                        </h4>
                    </div>
                    <div id="interfaceResponse" class="panel-collapse collapse in">
                        <div class="panel-body">
                            <table id="interfaceResponseTable">
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

#include("../include/footer.html")

<script>
    var anInterface = JSON.parse('${json(anInterface)}');
    var fieldDataTypes = JSON.parse('${json(fieldDataTypes)}');
</script>
<script type="text/javascript">
    var setting = {
        view: {
            addHoverDom: addHoverDom,
            removeHoverDom: removeHoverDom,
            selectedMulti: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        edit: {
            enable: true
        }
    };

    var zNodes = [
        {id: 1, pId: 0, name: "pNode 1", open: true},
        {id: 11, pId: 1, name: "pNode 11"},
        {id: 111, pId: 11, name: " sNode 111", "aaa": "bbb"},
        {id: 112, pId: 11, name: "sNode 112"},
        {id: 113, pId: 11, name: "sNode 113"},
        {id: 114, pId: 11, name: "sNode 114"},
        {id: 12, pId: 1, name: "pNode 12"},
        {id: 121, pId: 12, name: "sNode 121"},
        {id: 122, pId: 12, name: "sNode 122"},
        {id: 123, pId: 12, name: "sNode 123"},
        {id: 124, pId: 12, name: "sNode 124"},
        {id: 13, pId: 1, name: "pNode 13", isParent: true},
        {id: 2, pId: 0, name: "pNode 2"},
        {id: 21, pId: 2, name: "pNode 21", open: true},
        {id: 211, pId: 21, name: "sNode 211"},
        {id: 212, pId: 21, name: "sNode 212"},
        {id: 213, pId: 21, name: "sNode 213"},
        {id: 214, pId: 21, name: "sNode 214"},
        {id: 22, pId: 2, name: "pNode 22"},
        {id: 221, pId: 22, name: "sNode 221"},
        {id: 222, pId: 22, name: "sNode 222"},
        {id: 223, pId: 22, name: "sNode 223"},
        {id: 224, pId: 22, name: "sNode 224"},
        {id: 23, pId: 2, name: "pNode 23"},
        {id: 231, pId: 23, name: "sNode 231"},
        {id: 232, pId: 23, name: "sNode 232"},
        {id: 233, pId: 23, name: "sNode 233"},
        {id: 234, pId: 23, name: "sNode 234"},
        {id: 3, pId: 0, name: "pNode 3", isParent: true}
    ];
    var treeObj;
    $(document).ready(function () {
        treeObj = $.fn.zTree.init($("#treeDemo"), setting, zNodes);
        treeObj.expandAll(true);
    });

    var newCount = 1;

    function addHoverDom(treeId, treeNode) {
        var sObj = $("#" + treeNode.tId + "_span");
        if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
        var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
            + "' title='add node' onfocus='this.blur();'></span>";
        sObj.after(addStr);
        var btn = $("#addBtn_" + treeNode.tId);
        if (btn) btn.bind("click", function () {
            treeObj.addNodes(treeNode, {id: (100 + newCount), pId: treeNode.id, name: "new node" + (newCount++)});
            return false;
        });
    };

    function removeHoverDom(treeId, treeNode) {
        $("#addBtn_" + treeNode.tId).unbind().remove();
    };
    //-->
</script>

<script type="text-x-handlebars-template" id="template-interfaceInfo">
    <div class="row">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h4 class="panel-title">
                    <a data-toggle="collapse" data-parent="#accordion" href="#interfaceInfo">
                        接口信息
                    </a>
                </h4>
            </div>
            <div id="interfaceInfo" class="panel-collapse collapse in">
                <div class="panel-body">
                    <form class="form-horizontal">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">所属功能</label>
                            <div class="col-sm-10">
                                <p class="form-control-static">${anInterface.function.name}</p>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-2 control-label">接口名</label>
                            <div class="col-sm-10">
                                <p class="form-control-static">${anInterface.name}</p>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-2 control-label">URL</label>
                            <div class="col-sm-10">
                                <p class="form-control-static">${anInterface.url}</p>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</script>
<script>
    $(function () {
        var projectId = anInterface.function.project.id;
        initInterfaceInfo(anInterface);
    });

    function initInterfaceInfo(interfaceInfo) {
        var source = $('#template-interfaceInfo').html();//获取到html结构
        var template = Handlebars.compile(source);//编译成模板
        //生成完成的html结构
        var html = template(interfaceInfo);
        var $container = $('div#right-view');
        $container.prepend(html);
    }

    function initLeftFunctionView(projectId) {
        //渲染左侧功能列表-接口列表
        $.get(pathPrefix + '/getInterfaces?projectId=' + projectId, function (data, status) {
            if (data && data.result === 100) {
                var interfaceList = data.data;
                var source = $('#template-interfaceList').html();//获取到html结构
                var template = Handlebars.compile(source);//编译成模板
                //生成完成的html结构
                var html = template(interfaceList);
                var $container = $('div#interfaceList').find('.panel-body').eq(0);
                $container.html(html);
            }
        });
    }
</script>

<script>
    var interfaceRequestTable;
    var interfaceResponseTable;
    var generatorId = 1;

    function genID() {
        generatorId = generatorId + 1;
        return generatorId;
    }

    $(function () {
        var interfaceId = anInterface.id;
        initParams(interfaceId);
    });

    function initParams(interfaceId) {
//获取指定接口的参数
        $.get(pathPrefix + '/getParams?id=' + interfaceId, function (data, status) {
            if (data && data.result === 100) {
                var $data = data.data;
                if ($data === undefined || $data === null) {
                    $data = [];
                }
                console.log($data);

                var $request = [];
                var $response = [];


                $data.forEach(function ($element) {
                    if ($element.id && generatorId < $element.id) {
                        generatorId = $element.id;
                    }

                    if ($element.type === 'REQUEST') {
                        $request.push($element)
                    } else if ($element.type === 'RESPONSE') {
                        $response.push($element)
                    }
                });

                //渲染请求信息参数
                interfaceRequestTable = $('#interfaceRequestTable');
                initTable(interfaceRequestTable, $request);

                //渲染响应信息参数
                interfaceResponseTable = $('#interfaceResponseTable');
                initTable(interfaceResponseTable, $response);
            }
        });
    }

    function initTable($table, _tableData) {
        $table.bootstrapTable({
            columns: [
                {
                    field: 'operator', title: '', width: '80px', formatter: function (value, row, index) {
                        var arr = [];
                        var del = '<button onclick="delRowByBtn(this);" data-id="' + row.id + '" class="btn btn-danger btn-xs"><i class="fa fa-minus" aria-hidden="true"></i></button>';
                        var add = '<button onclick="addRowByBtn(this);" data-id="' + row.id + '" class="btn btn-primary btn-xs"><i class="fa fa-plus" aria-hidden="true"></i></button>';

                        // arr.push(view);
                        arr.push(del);
                        arr.push(' ');
                        arr.push(add);
                        return arr.join('');

                    }
                },
                {
                    field: 'name', title: '字段名',
                    editable: {
                        type: 'text',
                        title: '字段名',
                        mode: "inline",
                        showbuttons: false,
                        validate: function (v) {
                            if (!v) return '字段名不能为空';

                        }
                    }
                },
                {
                    field: 'dataType', title: '数据类型', editable: {
                        type: 'select',
                        title: '数据类型',
                        mode: "inline",
                        showbuttons: false,
                        source: fieldDataTypes
                    }
                },
                {
                    field: 'defaultValue', title: '默认值',
                    editable: {
                        type: 'text',
                        mode: "inline",
                        title: '默认值',
                        showbuttons: false,
                    }
                },
                {
                    field: 'required', title: '是否必须', editable: {
                        type: 'select',
                        title: '是否必须',
                        mode: "inline",
                        showbuttons: false,
                        source: [{value: 0, text: "非必填"}, {value: 1, text: "必填"}]
                    },
                }, {
                    field: 'description', title: '描述',
                    editable: {
                        type: 'text',
                        mode: "inline",
                        title: '描述',
                        showbuttons: false,
                    }
                },

            ],
            data: _tableData,
            //在哪一列展开树形
            treeShowField: 'name',
            //指定父id列
            parentIdField: 'pid',

            onResetView: function (data) {
                console.log('load');
                $table.treegrid({
                    initialState: 'expanded',// 所有节点都折叠
                    // initialState: 'expanded',// 所有节点都展开，默认展开
                    treeColumn: 1,
                    expanderExpandedClass: 'glyphicon glyphicon-minus',  //图标样式
                    expanderCollapsedClass: 'glyphicon glyphicon-plus',
                    onChange: function () {
                        $table.bootstrapTable('resetWidth');
                    }
                });

                //只展开树形的第一级节点
                $table.treegrid('getRootNodes').treegrid('expand');

            },
            onCheck: function (row) {
                var datas = $table.bootstrapTable('getData');
                // 勾选子类
                selectChilds(datas, row, "id", "pid", true);

                // 勾选父类
                selectParentChecked(datas, row, "id", "pid")

                // 刷新数据
                $table.bootstrapTable('load', datas);
            },

            onUncheck: function (row) {
                var datas = $table.bootstrapTable('getData');
                selectChilds(datas, row, "id", "pid", false);
                $table.bootstrapTable('load', datas);
            },
            // bootstrap-table-treetreegrid.js 插件配置 -- end
        });
    }

    function importFromJson(tableId) {
        //
        layer.prompt({formType: 2, maxlength: 10000, title: '导入JSON'}, function (val, index) {
            $.ajax({
                type: 'POST',
                url: pathPrefix + "/importJson",
                data: {json: val},
                dataType: 'json',
                success: function (result) {
                    if (result) {
                        if (result.result && result.result === 100) {
                            $('#' + tableId).bootstrapTable('load', result.data);
                            toastr.success('JSON导入成功');
                            layer.close(index);
                        } else {
                            toastr.error('JSON导入失败：' + result.message);
                        }
                    } else {
                        toastr.error('JSON导入失败：');
                    }
                },
            });
        });
    }

    function saveRowsByTableId(tableId) {
        var _data = $('#' + tableId).bootstrapTable('getData');
        console.log(_data);

        var params = [];
        if (_data) {
            _data.forEach(function (item) {
                item = {
                    id: item.id,
                    name: item.name,
                    dataType: item.dataType,
                    defaultValue: item.defaultValue,
                    required: item.required,
                    description: item.description,
                    type: item.type,
                    pid: item.pid,
                }
                params.push(item);
            });
        }

        var type = tableId == 'interfaceRequestTable' ? 'REQUEST' : 'RESPONSE';
        $.ajax({
            type: 'POST',
            url: pathPrefix + "/params",
            data: {params: JSON.stringify(params), interfaceId: anInterface.id, type: type},
            dataType: 'json',
            success: function (result) {
                if (result) {
                    if (result.result && result.result == 100) {
                        toastr.success('保存成功');
                    } else {
                        toastr.error('保存失败：' + result.message);
                    }
                } else {
                    toastr.error('保存失败：');
                }
            },
        });
    }

    function delRowByBtn(obj) {
        var _obj = $(obj);
        var id = _obj.attr('data-id');
        var _table = _obj.parents('table').eq(0);

        _table.bootstrapTable('remove', {
            field: 'id',
            values: [parseInt(id)]
        });
        toastr.success('删除成功');
    }

    function addRowByTableId(tableId) {
        var _table = $('#' + tableId);
        var id = genID();
        addRow(_table, id);
    }

    function addRow(_table, id) {
        if (id) {
            id = parseInt(id);
        }
        var _data = _table.bootstrapTable('getData');
        var row = {};
        _data.forEach(function (_item) {
            if (_item.id === id) {
                row = _item;
            }
        });
        var newRow;
        var _dataType = row.dataType;
        if (_dataType == 'Object' || _dataType == 'Array') {
            newRow = initRow(row.id);
        } else {
            newRow = initRow(row.pid);
        }
        _table.bootstrapTable('append', newRow);
        console.log('add', id, row, newRow);
        toastr.success('添加成功');
    }

    function addRowByBtn(obj) {
        var _obj = $(obj);
        var id = _obj.attr('data-id');
        var _table = _obj.parents('table').eq(0);
        addRow(_table, id);
    }

    function initRow(pid) {
        if (!pid) {
            pid = 0;
        }
        return {
            id: genID(),
            pid: parseInt(pid),
            name: 'Item 1',
            dataType: 'String',
            defaultValue: 'String',
            required: 0,
            type: 'REQUEST',
        };
    }

</script>

</body>
</html>